package com.haiyi.software.app.basic;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;

import android.os.Bundle;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.haiyi.software.app.MainApplication;
import com.haiyi.software.entity.UserInfo;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.ResponseHandlerInterface;

public abstract class ActivityPersonalBasicCancelFollow extends
		ActivityPersonalBasicMenu {

	private static final String str_requestUrlFollow = "cancel_gz.php";

	protected abstract void cancelFollowReturn(JsonObject jsonReturn);

	private Boolean isWork = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO 自动生成的方法存根
		super.onCreate(savedInstanceState);
	}

	protected void cancelFollow(String uid, String uname) {

		UserInfo myInfo = MainApplication.getInstance().getMineUserInfo();

		if (myInfo != null) {

			Map<String, Object> validator = new HashMap<String, Object>();

			validator.put("uid", myInfo.getUid());
			validator.put("uname", myInfo.getUname());
			validator.put("pwd", myInfo.getPwd());
			validator.put("uguid", myInfo.getUguid());

			Map<String, Object> body = new HashMap<String, Object>();

			body.put("uid", uid);
			body.put("uname", uname);

			Map<String, Object> args = new HashMap<String, Object>();
			args.put("validator", validator);
			args.put("body", body);

			Gson gson = new Gson();
			String s = gson.toJson(args);
			this.cancelFollowRequestNetworkData(s);
		}

	}

	private synchronized void cancelFollowRequestNetworkData(Object... args) {

		if (!isWork) {

			AsyncHttpClient client = MainApplication.getInstance()
					.getAsyncHttpClient();

			RequestParams params = new RequestParams();

			params.put("args", args[0]);

			client.post(str_server + str_requestUrlFollow, params, rpHandler);
		}
	}

	private ResponseHandlerInterface rpHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int statusCode, Header[] headers,
				byte[] responseBody) {

			isWork = false;
			try {

				String str_jsonReturn = new String(responseBody, "UTF-8");

				Log.i("rbody", str_jsonReturn);

				JsonParser parse = new JsonParser();

				JsonObject jsonReturn = parse.parse(str_jsonReturn)
						.getAsJsonObject();

				cancelFollowReturn(jsonReturn);

			} catch (Exception e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
				requestError();
			}
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] responseBody, Throwable error) {

			isWork = false;
			requestError();
		}
	};
}
